<?php
class PostSaveEditAction extends UserAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'json';
	}
	
	protected function afterConstruct()
	{
		$this->parseDtds('post','edit');
	}
	
	public function execute()
	{
		$id				= $this->context->post('id');
		$data			= $this->getValidData();
		$data			= C('PostUtil')->RemoveAllXSS($data);
		
		$postService	= new PostService();
		if(is_numeric($id) && $id)
		{
			$tmp	= $postService->get($id);
			if($tmp && $tmp['user_id']==$this->data['user']['id'])
			{
				if($this->data['config']['system']['autoadmit'])
				{
					$data['status']		= 1;
				}
				else
				{
					$data['status']		= 0;
				}
				$data['modified']	= date('Y-m-d H:i:s');
				$postService->update($id,$data);
				$this->code	= 200;
				$this->data['forward'] = C('LtUrl')->generate('Post', 'View', array('id'=>$id));
			}
			else
			{
				$this->code	= 400;
			}
		}
		else
		{
			$data['visit_num']		= 1;
			$data['user_id']		= $this->data['user']['id'];
			$data['username']		= $this->data['user']['username'];
			$data['type']			= 1;
			$data['last_post']		= $this->data['user']['username'];
			$data['modified']		= date('Y-m-d H:i:s');
			$data['last_updated']	= date('Y-m-d H:i:s');
			if($this->data['config']['system']['autoadmit'])
			{
				$data['status']		= 1;
			}
			else
			{
				$data['status']		= 0;
			}
			$id	= $postService->add($data);
			if($id>0)
			{
				$this->code	= 200;
				$this->data['forward'] = C('LtUrl')->generate('Post', 'View', array('id'=>$id));
			}
			else
			{
				$this->code	= 400;
			}
		}
	}
}
